package com.mawendaxiong.bloggateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class BlogAdminFilter extends ZuulFilter {
    private static ConcurrentHashMap<String, Object> authorMap = new ConcurrentHashMap<>(16);
    static {
        authorMap.put("mawendaxiong","123wjj");
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String author = request.getParameter("author");
        String password = request.getParameter("password");
        if (StringUtils.isBlank(author) || StringUtils.isBlank(password)) {
            getRequestContext(currentContext,"请提供相关凭证");
        } else {
            if (null == authorMap.get(author)) {
                getRequestContext(currentContext,"改作者无权限");
            }else {
                String pwd = authorMap.get(author).toString();
                if (!pwd.equals(password)){
                    getRequestContext(currentContext,"密码错误");
                }
            }
        }
        return null;
    }

    private void getRequestContext(RequestContext currentContext, String message) {
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(401);
        try {
            currentContext.setResponseBody(new String(message.getBytes(),"Utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
